|
|
|
|
|
|
|
After dealing with probably thousands of API questions over the past few years, one thing has become apparent to me. Virtually every mistake that Visual Basic programmers make when calling API functions has something to do with the ByVal keyword. Either it's there when it shouldn't be or it's missing. |
|
|
|
|
|
|
|
|
It is essential that you understand exactly what this keyword does and how to use it if you are going to be able to create Visual Basic declarations for API and DLL functions. |
|
|
|
|
|
|
|
|
What Does ByVal Do?
The Simple Explanation |
|
|
|
|
|
|
|
|
In a nutshell, the ByVal keyword tells Visual Basic that a parameter should be passed by value, meaning that the actual value of the variable should be passed to the function. When the ByVal keyword is missing, the parameter is passed as if the ByRef keyword was used, which is referred to as passing the parameter by reference. The ByValSp.vbp project (on the CD that accompanies this book) illustrates the difference between the two types of parameter passing. |
|
|
|
|
|
|
|
|
' ByValSimple Example
' Copyright © 1998 by Desaware Inc. All Rights Reserved
Option Explicit
Private Sub Command1_Click()
Dim myvar As Long
myvar = 5
Call CalledByVal(myvar)
Debug.Print "After call ByVal: " & myvar
Call CalledByRef(myvar)
Debug.Print "After call ByRef: " & myvar
End Sub
Private Sub CalledByRef(x As Long)
x = x + 1
End Sub
Private Sub CalledByVal(ByVal x As Long)
x = x + 1
End Sub |
|
|
|
|
|
|
|
|
The result appears as follows: |
|
|
|
|
|